package cn.rdq.common.util;

import cn.rdq.common.exception.BaseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
  private static ObjectMapper objectMapper;

  private JacksonUtil() {
  }

  /**
   * 使用泛型方法，把json字符串转换为相应的JavaBean对象。
   * (1)转换为普通JavaBean：readValue(json,Student.class)
   * (2)转换为List,如List,将第二个参数传递为Student
   * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
   *
   * @param jsonStr not null
   * @param valueType not null
   * @return T
   */
  public static <T> T readValue(String jsonStr, Class<T> valueType) {
    if (objectMapper == null) {
        objectMapper = new ObjectMapper();
    }

    try {
        return objectMapper.readValue(jsonStr, valueType);
    } catch (Exception e) {
        throw new BaseException("反序列化异常", e);
    }

  }

  /**.
   * json数组转List
   *
   * @param jsonStr  not null
   * @param valueTypeRef not null
   * @return T
   */
  public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {
    if (objectMapper == null) {
        objectMapper = new ObjectMapper();
    }

    try {
        return objectMapper.readValue(jsonStr, valueTypeRef);
    } catch (Exception e) {
        throw new BaseException("反序列化异常", e);
    }
  }

  /**.
   * 把JavaBean转换为json字符串
   *
   * @param object  not null
   * @return
   */
  public static String toJson(Object object) {
    if (objectMapper == null) {
      objectMapper = new ObjectMapper();
    }

    try {
        return objectMapper.writeValueAsString(object);
    } catch (Exception e) {
        throw new BaseException("序列化异常", e);
    }
  }
}
